const express = require("express")
const userCenter = express.Router() //创建路由
const multer = require("multer")
const User = require("../mod/user")
const Rank = require("../mod/rank")
const Pand = require("../mod/pandant")
const fs = require("fs")
const path = require("path")
var filePath = path.join(__dirname, "")

//用户对轻音乐的设置
userCenter.post("/getisShow",async (req,res)=>{
    let {
        _id,
        user_music_isplay
    } = req.body


    let data = await User.updateOne({
        _id
    }, {
        user_music_isplay
    })
    if (data) {
        let datalist = await User.findOne({
            _id
        })
        if (datalist) {
            // console.log(datalist)
            return res.status(200).json({
                datalist,
                message: "轻音乐播放设置成功"
            })
        } else {
            return res.status(201).json({
                message: "轻音乐播放设置失败，请重新设置"
            })
        }
    }

    res.status(202).json({
        message: "轻音乐播放设置失败，请重新设置"
    })




})

//用户设置所学科目展示
userCenter.post("/getProjectarr",async (req,res)=>{
    //所需参数  user_id, user_grade_arr
    let {
        _id,
        user_project_arr,
        user_type_arr
    } = req.body

    //先对user_type_arr做处理
    for (let i = 0; i < user_type_arr.length; i++) {
        switch (user_type_arr[i]) {
            case "1":
                user_type_arr.splice(i, 1, {
                    value: "1",
                    label: "日常测试"
                });
                break;
            case "2":
                user_type_arr.splice(i, 1, {
                    value: "2",
                    label: "周测"
                });
                break;
            case "3":
                user_type_arr.splice(i, 1, {
                    value: "3",
                    label: "月测"
                });
                break;
        }
    }
    
    let datalist2=user_type_arr
    let arritem2 = {}
    for (let i = 0; i < datalist2.length - 1; i++) {
        for (let j = 0; j < datalist2.length - i - 1; j++) {
            if (datalist2[j].value > datalist2[j + 1].value) {
                arritem2 = datalist2[j]
                datalist2[j] = datalist2[j + 1]
                datalist2[j + 1] = arritem2
            }
        }
    }

    // console.log(user_type_arr)
    //生成数组
    for (let i = 0; i < user_project_arr.length; i++) {
        switch (user_project_arr[i]) {
            case "1":
                user_project_arr.splice(i, 1, {
                    value: "1",
                    label: "语文",
                    children: user_type_arr
                });
                break;
            case "2":
                user_project_arr.splice(i, 1,  {
                    value: "2",
                    label: "数学",
                    children: user_type_arr
                  });
                break;
            case "3":
                user_project_arr.splice(i, 1,     {
                    value: "3",
                    label: "英语",
                    children:user_type_arr
        });
                break;
            case "4":
                user_project_arr.splice(i, 1, {
                    value: "4",
                    label: "政治",
                    children:user_type_arr
                });
                break;
            case "5":
                user_project_arr.splice(i, 1, {
                    value: "5",
                    label: "历史",
                    children: user_type_arr
                });
                break;
            case "6":
                user_project_arr.splice(i, 1, {
                    value: "6",
                    label: "地理",
                    children:user_type_arr
                });
                break;
            case "7":
                user_project_arr.splice(i, 1,{
                    value: "7",
                    label: "物理",
                    children:user_type_arr
                });
                break;
            case "8":
                user_project_arr.splice(i, 1, {
                    value: "8",
                    label: "化学",
                    children:user_type_arr
                });
                break;
            case "9":
                user_project_arr.splice(i, 1, {
                    value: "9",
                    label: "生物",
                    children:user_type_arr
                });
                break;
        }
    }

    // console.log(user_project_arr)

    //正序
    let datalist=user_project_arr
    let arritem = {}
    for (let i = 0; i < datalist.length - 1; i++) {
        for (let j = 0; j < datalist.length - i - 1; j++) {
            if (datalist[j].value > datalist[j + 1].value) {
                arritem = datalist[j]
                datalist[j] = datalist[j + 1]
                datalist[j + 1] = arritem
            }
        }
    }

    user_project_arr=datalist
    // console.log(user_project_arr)
        // console.log(user_grade_arr)
        let data = await User.updateOne({
            _id
        }, {
            user_project_arr
        })
        if (data) {
            let datalist = await User.findOne({
                _id
            })
            if (datalist) {
                // console.log(datalist)
                return res.status(200).json({
                    datalist,
                    message: "所学科目展示设置成功"
                })
            } else {
                return res.status(201).json({
                    message: "所学科目展示设置失败，请重新设置"
                })
            }
        }
    
        res.status(202).json({
            message: "所学科目展示设置失败，请重新设置"
        })



})

//用户设置所学年级展示
userCenter.post("/getGardearr", async (req, res) => {
    //所需参数  user_id, user_grade_arr
    let {
        _id,
        user_grade_arr
    } = req.body

    // console.log(user_grade_arr) //["0","1"]

    for (let i = 0; i < user_grade_arr.length; i++) {
        switch (user_grade_arr[i]) {
            case "0":
                user_grade_arr.splice(i, 1, {
                    value: 0,
                    describe: "学前教育"
                });
                break;
            case "1":
                user_grade_arr.splice(i, 1, {
                    value: 1,
                    describe: "一年级"
                });
                break;
            case "2":
                user_grade_arr.splice(i, 1, {
                    value: 2,
                    describe: "二年级"
                });
                break;
            case "3":
                user_grade_arr.splice(i, 1, {
                    value: 3,
                    describe: "三年级"
                });
                break;
            case "4":
                user_grade_arr.splice(i, 1, {
                    value: 4,
                    describe: "四年级"
                });
                break;
            case "5":
                user_grade_arr.splice(i, 1, {
                    value: 5,
                    describe: "五年级"
                });
                break;
            case "6":
                user_grade_arr.splice(i, 1, {
                    value: 6,
                    describe: "六年级"
                });
                break;
            case "7":
                user_grade_arr.splice(i, 1, {
                    value: 7,
                    describe: "七年级"
                });
                break;
            case "8":
                user_grade_arr.splice(i, 1, {
                    value: 8,
                    describe: "八年级"
                });
                break;
            case "9":
                user_grade_arr.splice(i, 1, {
                    value: 9,
                    describe: "九年级"
                });
                break;
            case "10":
                user_grade_arr.splice(i, 1, {
                    value: 10,
                    describe: "高一"
                });
                break;
            case "11":
                user_grade_arr.splice(i, 1, {
                    value: 11,
                    describe: "高二"
                });
                break;
            case "12":
                user_grade_arr.splice(i, 1, {
                    value: 12,
                    describe: "高三"
                });
                break;
        }
    }

    let arritem = {}
    for (let i = 0; i < user_grade_arr.length - 1; i++) {
        for (let j = 0; j < user_grade_arr.length - i - 1; j++) {
            if (user_grade_arr[j].value > user_grade_arr[j + 1].value) {
                arritem = user_grade_arr[j]
                user_grade_arr[j] = user_grade_arr[j + 1]
                user_grade_arr[j + 1] = arritem
            }
        }
    }

    // console.log(user_grade_arr)
    let data = await User.updateOne({
        _id
    }, {
        user_grade_arr
    })
    if (data) {
        let datalist = await User.findOne({
            _id
        })
        if (datalist) {
            // console.log(datalist)
            return res.status(200).json({
                datalist,
                message: "所学年级展示设置成功"
            })
        } else {
            return res.status(201).json({
                message: "所学年级展示设置失败，请重新设置"
            })
        }
    }

    res.status(202).json({
        message: "所学年级展示设置失败，请重新设置"
    })


})

//用户对页面灰度的设置保存,或修改
userCenter.post('/postFlutter', async (req, res) => {
    //需要的参数 user_id ,flutter_number
    let {
        user_id
    } = req.body
    let datalist = await User.updateOne({
        _id: user_id
    }, req.body)
    if (datalist) {
        return res.status(200).json({
            datalist,
            message: "界面灰度设置成功"
        })
    }
    res.status(201).json({
        message: "界面灰度设置失败，请重试"
    })
})


//图片上传部分
var storage = multer.diskStorage({
    //设置上传后的文件路径
    destination: function (req, file, cb) {
        cb(null, './public/user')
    },
    //给上传文件重命名，以防命名重复
    filename: function (req, file, cb) {
        cb(null, Date.now() + file.originalname)
    }
})

var upload = multer({
    storage: storage
})


//获取最近的提交成绩记录
userCenter.get("/getupgardjl", async (req, res) => {
    //需要的参数 用户id 
    // console.log(req.query)
    let {
        user_id
    } = req.query

    // console.log(user_id)
    let datalist = await Rank.find({
        user_id
    }, {
        push_time: 1,
        test_name: 1
    }).populate("user_id").limit(5).sort({
        'push_time': -1
    })
    // console.log(datalist)
    if (datalist) {
        res.status(200).json({
            datalist
        })
    }

})


//上传头像
userCenter.post('/uploadimage', upload.single('file'), async (req, res) => {
    let _id = req.query._id
    let headerimg = "http://localhost:8888/user/" + req.file.filename //获取上传后改了的最终名字，数据库中读取
    // 先找到原来的
    let data1 = await User.findOne({
        _id
    })


    let oldheaderimg = data1.headerimg.replace("http://localhost:8888/user/", "")
    // console.log(oldheaderimg)
    if (oldheaderimg !== "user.jpg") {
        //   console.log("即将删除原照片")
        filePath = filePath.replace("code", "public/user/")

        // console.log(`${filePath}+${oldheaderimg}`)
        // console.log(pand_url)
        fs.unlink(`${filePath}${oldheaderimg}`, (err) => {
            if (err) {
                // console.log(`${oldheaderimg}文件删除失败`)
            }
            // console.log("原头像删除o'kok")
        })
    }

    User.updateOne({
        _id: _id
    }, {
        headerimg: headerimg
    }, async (err, data) => {
        if (err) {
            res.status(202).send({
                message: "上传失败"
            })
        } else {
            //查询新的数据，重新返回
            let data1 = await User.findOne({
                _id
            })
            res.status(200).send({
                data1
            })
        }
    })
})

//上传本次成绩
userCenter.post("/upGarde", async (req, res) => {
    // console.log(req.body)
    let {
        _id,
        test_grade,
        test_project,
        test_type,
        test_rank1,
        test_rank2,
        class_ranking,
        school_ranking,
        area_ranking,
        city_ranking,
        test_note
    } = req.body

    let test_rank = 0
    push_time = Date.now() + ""
    test_note = test_note + ""
    test_rank = test_rank - 0
    test_rank1 = test_rank1 - 0
    test_rank2 = test_rank2 - 0
    test_rank = Math.round(test_rank1 * 100 / test_rank2)
    test_grade = test_grade - 0
    test_project = test_project + "" - 0
    test_type = test_type - 0
    class_ranking = class_ranking - 0
    school_ranking = school_ranking - 0
    area_ranking = area_ranking - 0
    city_ranking = city_ranking - 0

    //拼接test——name
    //年级
    // let num1 = ""
    switch (test_grade) {
        case 0:
            num1 = "学前教育";
            break;
        case 1:
            num1 = "一年级";
            break;
        case 2:
            num1 = "二年级";
            break;
        case 3:
            num1 = "三年级";
            break;
        case 4:
            num1 = "四年级";
            break;
        case 5:
            num1 = "五年级";
            break;
        case 6:
            num1 = "六年级";
            break;
        case 7:
            num1 = "七年级";
            break;
        case 8:
            num1 = "八年级";
            break;
        case 9:
            num1 = "九年级";
            break;
        case 10:
            num1 = "高一";
            break;
        case 11:
            num1 = "高二";
            break;
        case 12:
            num1 = "高三";
            break;
    }
    // console.log(num1)

    //科目
    let num2 = ""
    switch (test_project) {
        case 1:
            num2 = "语文";
            break;
        case 2:
            num2 = "数学";
            break;
        case 3:
            num2 = "英语";
            break;
        case 4:
            num2 = "历史";
            break;
        case 5:
            num2 = "地理";
            break;
        case 6:
            num2 = "生物";
            break;
        case 7:
            num2 = "物理";
            break;
        case 8:
            num2 = "化学";
            break;
        case 9:
            num2 = "生物";
            break;
    }
    // console.log(num2)


    //类型
    let num4 = ""
    switch (test_type) {
        case 1:
            num4 = "日常测试";
            break;
        case 2:
            num4 = "周测";
            break;
        case 3:
            num4 = "月测";
            break;
    }
	
	//格式化时间的函数
	function momtime(){
	        var date=new Date();
	        var year=date.getFullYear();
	        /* 在日期格式中，月份是从0开始的，因此要加0
	         * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
	         * */
	        var month= date.getMonth()+1<10 ? "0"+(date.getMonth()+1) : date.getMonth()+1;
	        var day=date.getDate()<10 ? "0"+date.getDate() : date.getDate();
	        var hours=date.getHours()<10 ? "0"+date.getHours() : date.getHours();
	        var minutes=date.getMinutes()<10 ? "0"+date.getMinutes() : date.getMinutes();
	        var seconds=date.getSeconds()<10 ? "0"+date.getSeconds() : date.getSeconds();
	        // 拼接
	        return year+"-"+month+"-"+day+" "+hours+":"+minutes+":"+seconds;
	
	        }

//提交时间
let puttime=momtime()
   
    //用户名
    let num3 = await User.findOne({
        _id
    })

    let test_name = `${num1}-${num2}-${num4}-在${puttime}提交-${num3.username}`
    // console.log(test_name)
    let data = null
    try {
        data = await new Rank({
            user_id: _id,
            test_grade,
            test_project,
            test_type,
            test_name,
            test_rank,
            test_rank1,
            test_rank2,
            class_ranking,
            school_ranking,
            area_ranking,
            city_ranking,
            test_note,
            push_time
        }).save()
    } catch (error) {
        res.status(201).send({
            message: "err"
        })
    }

    if (data) {
        res.status(200).send({
            data,
            message: "上传ok"
        })
    } else {
        res.status(201).send({
            message: "err"
        })
    }
})


//获取全部的头像挂件
userCenter.get("/pands", async (req, res) => {
    let total = await Pand.countDocuments({})
    let data = await Pand.find({})
    if (data) {
        res.status(200).json({
            message: "获取头部挂件成功",
            data,
            total
        })
    }
})

//设置头像挂件

userCenter.post("/setpand", async (req, res) => {
    //需要传入用户_id,挂件 pand_id
    // console.log(req.body)
    let {
        _id,
        pand_url
    } = req.body

    let data = await User.updateOne({
        _id
    }, {
        pand_url
    })
    if (data) {
        res.status(200).json({
            message: "修改成功",
            data
        })
    } else {
        res.status(202).json({
            message: "修改失败，请重试"
        })
    }
})




module.exports = userCenter